import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as API from "../api/http";

//存放数据
let initialState = {
    shoplist: [],//表格数据
}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步方法
        //获取表格数据
        getlist(state, action) {
            state.shoplist = action.payload
        },

        //添加数据
        t_addlist(state: any, action): any {
            state.shoplist.push(action.payload)
        },

        //编辑数据
        t_updatelist(state: any, action: any) {
            let i = state.shoplist.findIndex((item: any) => {
                return item.id == action.payload.id
            })
            state.shoplist[i] = action.payload
        },

        //删除数据
        t_dellist(state: any, action: any) {
            state.shoplist = state.shoplist.filter((item: any) => {
                return item.id !== action.payload
            })
        }

    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

//异步方法 获取数据
export let async_list = createAsyncThunk('async_list', async (_, store) => {
    //调取接口
    let res = await API.http_getlist()
    //同步修改异步
    store.dispatch(actionfn.getlist(res))
})

//异步方法 搜索数据
export let async_searchlist = createAsyncThunk('async_searchlist', async (obj: any, store) => {
    //调取接口
    let res = await API.search_list(obj)
    //同步修改异步
    store.dispatch(actionfn.getlist(res))
})

//异步方法 添加数据
export let async_addlist = createAsyncThunk('async_addlist', async (obj, store) => {
    //调取接口
    let res = await API.add_list(obj)
    //同步修改异步
    store.dispatch(actionfn.t_addlist(res))
})

//异步方法 编辑数据
export let async_updatelist = createAsyncThunk('async_updatelist', async (obj, store) => {
    //调取接口
    let res = await API.update_list(obj)
    //同步修改异步
    store.dispatch(actionfn.t_updatelist(res))
})

//异步方法 删除数据
export let async_dellist = createAsyncThunk('async_dellist', async (id, store) => {
    //调取接口
    await API.del_list(id)
    store.dispatch(actionfn.t_dellist(id))
})